from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import ListAPIView
from rest_framework import serializers
from api.authentication.auth import UserAuthentication, GeneralAuthentication
from django.forms import model_to_dict
from api.serializer.account import LoginSerializer, UsernameEmailSerializer, UsernamephoneSerializer, \
    ResetPasswordSerializer, SetPasswordSerializer
from api.views import SocialModelSerializer
from api.pagination.pages import SocialListLimitOffsetPagination, MaxBaseFilterBackend
import datetime
from api import models
import uuid


def user_list_all(user_object):
    queryset = models.UserOther.objects
    user_qq = queryset.filter(user=user_object, status=2).exists()
    user_wx = queryset.filter(user=user_object, status=1).exists()
    user_wb = queryset.filter(user=user_object, status=3).exists()
    context = {'status': True,
               'data': model_to_dict(user_object,
                                     ['id', 'token', 'username', 'avatar', "email", "phone", "password"]),
               'user_other': {"qq": user_qq, "wx": user_wx, "wb": user_wb}
               }
    return context


class LoginView(APIView):
    def post(self, request, *args, **kwargs):
        ser = LoginSerializer(data=request.data)

        if not ser.is_valid():
            print(ser.errors)
            return Response({'status': False, 'message': ser.errors.get('code')[0]})
        phone = ser.validated_data.get('phone')

        user_object, flag = models.UserInfo.objects.get_or_create(phone=phone)
        exists = models.UserData.objects.filter(user=user_object).exists()
        if not exists:
            models.UserData.objects.create(user=user_object, birthday=datetime.datetime.now())
        user_object.token = str(uuid.uuid4())
        user_object.save()

        return Response(user_list_all(user_object))


class UsernameEmail(APIView):
    def post(self, request, *args, **kwargs):
        phone = request.data.get('phone')
        queryset = models.UserInfo.objects
        # 邮箱登录
        if not phone:
            request.data.pop('phone')
            ser = UsernameEmailSerializer(data=request.data)

        else:
            request.data.pop('email')
            ser = UsernamephoneSerializer(data=request.data)

        if not ser.is_valid():
            return Response({'status': False, 'message': ser.errors})
        user_object = queryset.filter(**ser.data).first()
        if not user_object:
            return Response({'status': False, "message": "账号或密码错误"})
        exists = models.UserData.objects.filter(user=user_object).exists()
        if not exists:
            models.UserData.objects.create(user=user_object, birthday=datetime.datetime.now())

        return Response(user_list_all(user_object))


class EmailAdd(APIView):
    authentication_classes = [UserAuthentication]

    def post(self, request, *args, **kwargs):
        email = request.data.get('email')
        exists = models.UserInfo.objects.filter(email=email).exists()
        if not exists:
            request.user.email = email
            request.user.save()
            return Response({'status': True, 'msg': request.user.email})
        return Response({'status': False, 'msg': "邮箱已存在"})


class ResetPasswordView(APIView):
    authentication_classes = [UserAuthentication]

    def post(self, request, *args, **kwargs):
        ser = ResetPasswordSerializer(data=request.data, context={'request': request})
        if not ser.is_valid():
            return Response({'status': False, 'message': ser.errors})
        request.user.password = ser.data.get('pwd1')
        request.user.save()
        return Response({'status': True, 'message': "修改成功"})


class UserNewsView(APIView):
    authentication_classes = [UserAuthentication]

    def get(self, request, *args, **kwargs):
        posts = models.Posts.objects
        posts_total = posts.filter(topic__isnull=True, user=request.user).count()
        total = [{
            "name": '帖子',
            "num": posts_total
        }, {
            "name": '动态',
            "num": posts.filter(status__isnull=True, user=request.user).count()
        }, {
            "name": '评论',
            "num": models.Comment.objects.filter(user=request.user).count()
        }, {
            "name": '粉丝',
            "num": models.Follow.objects.filter(user_follow=request.user, status=2).count()
        }]
        now_time = datetime.datetime.now() - datetime.timedelta(hours=24)
        topic_count = posts.filter(user=request.user, topic__isnull=True).filter(create_date__gt=now_time).count()

        posts = {
            'today': topic_count,
            'posts_total': posts_total
        }
        context = {
            "total": total,
            "posts": posts
        }
        return Response({'status': True, 'data': context})


class UserDataModelSerializer(serializers.ModelSerializer):
    userinfo = serializers.SerializerMethodField()

    class Meta:
        model = models.UserData
        fields = "__all__"

    def get_userinfo(self, obj):
        return model_to_dict(obj.user, ['username', 'avatar', "id"])


class UserDataView(ListAPIView):
    queryset = models.UserData.objects
    serializer_class = UserDataModelSerializer
    authentication_classes = [UserAuthentication]

    def get_queryset(self):
        return self.queryset.filter(user=self.request.user)

    def get(self, request, *args, **kwargs):
        response = super().get(request, *args, **kwargs)
        user_data = models.UserData
        sexArray = []
        emotionArray = []
        jobArray = []
        for sex, emotion in zip(user_data.sex_choices, user_data.emotion_choices):
            sexArray.append(sex[1])
            emotionArray.append(emotion[1])
        for job in user_data.job_choices:
            jobArray.append(job[1])
        result = {
            "sexArray": sexArray,
            "emotionArray": emotionArray,
            "jobArray": jobArray
        }
        response.data = {
            "result": result,
            "list": response.data
        }
        return response


class UserDataAddView(APIView):
    authentication_classes = [UserAuthentication]

    def post(self, request, *args, **kwargs):
        userinfo = request.data.pop('userinfo')
        request.user.username = userinfo['username']
        request.user.avatar = userinfo['avatar']
        request.user.save()
        models.UserData.objects.filter(id=request.data.get('id'), user=request.user).update(**request.data)

        return Response(user_list_all(request.user))


class UserSpaceModelSerializer(serializers.ModelSerializer):
    emotion = serializers.CharField(source="get_emotion_display")
    job = serializers.CharField(source="get_job_display")
    avatar = serializers.CharField(source="user.avatar")
    username = serializers.CharField(source="user.username")
    isFollow = serializers.SerializerMethodField()

    class Meta:
        model = models.UserData
        fields = "__all__"

    def get_isFollow(self, obj):
        user_object = self.context['request'].user
        if not user_object:
            return False
        if user_object == obj.user:
            return user_object.id
        return models.Follow.objects.filter(user=user_object, user_follow=obj.user).exists()


class UserSpaceView(ListAPIView):
    queryset = models.UserData.objects
    serializer_class = UserSpaceModelSerializer
    authentication_classes = [GeneralAuthentication]

    def get_queryset(self):
        pk = self.kwargs.get('pk')
        return self.queryset.filter(user_id=pk)

    def get(self, request, *args, **kwargs):
        response = super().get(request, *args, **kwargs)
        pk = kwargs.get('pk')

        total = [{
            "name": '帖子',
            "num": models.Posts.objects.filter(user_id=pk).count()
        }, {
            "name": '关注',
            "num": models.Follow.objects.filter(user_id=pk).count()
        }, {
            "name": '粉丝',
            "num": models.Follow.objects.filter(user_follow_id=pk, status=2).count()
        }]
        response.data = {
            "list": response.data,
            "total": total
        }
        return response


class UserPostsView(ListAPIView):
    queryset = models.Posts.objects
    serializer_class = SocialModelSerializer
    authentication_classes = [GeneralAuthentication]
    pagination_class = SocialListLimitOffsetPagination
    filter_backends = [MaxBaseFilterBackend]

    def get_queryset(self):
        status = self.request.GET.get('status', None)
        pk = self.kwargs.get('pk')
        if status:
            return self.queryset.filter(user_id=pk, topic__isnull=True)
        return self.queryset.filter(user_id=pk, status__isnull=True)


class UserOtherView(APIView):
    authentication_classes = [UserAuthentication]

    def post(self, request, *args, **kwargs):
        user_list = request.data
        user_other = models.UserOther.objects.filter(openid=user_list['openid']).first()
        if user_other:
            return Response({'status': False, 'msg': "已被绑定过了"})
        user_other = models.UserOther.objects.filter(user=request.user, status=user_list['status']).first()
        if user_other:
            return Response({'status': False, 'msg': "已绑定过了"})
        print(user_list)
        models.UserOther.objects.create(**user_list)
        return Response(user_list_all(request.user))


class SetPasswordView(APIView):
    authentication_classes = [UserAuthentication]

    def post(self, request, *args, **kwargs):
        ser = SetPasswordSerializer(data=request.data, context={'request': request})
        if not ser.is_valid():
            return Response({'status': False, "msg": "请求错误"})
        request.user.password = ser.data.get('pwd1')
        request.user.save()
        return Response(user_list_all(request.user))


class UserOtherListView(APIView):
    def post(self, request, *args, **kwargs):
        data = request.data
        user_other_object = models.UserOther.objects.filter(openid=data['openid'], status=data['status']).first()
        print(user_other_object, data)
        # 如果没有绑定
        if not user_other_object:
            return Response({'status': False, "msg": "登录失败请先创建账号"})
        user_object = models.UserInfo.objects.filter(id=user_other_object.user.id).first()
        return Response(user_list_all(user_object))
